import 'package:flutter/material.dart';
import 'package:Lter/screens/data/phone_list_item.dart';
import 'package:Lter/model/phone.dart';
import 'package:Lter/model/app.dart';
import 'package:Lter/util/toast.dart';

class PhoneScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return Widget_PhoneScreen_State();
  }
}

class Widget_PhoneScreen_State extends State<PhoneScreen> {
  var list = [];
  int page = 0;
  bool isLoading = false; //是否正在请求新数据
  bool showMore = false; //是否显示底部加载中提示
  bool offState = false; //是否显示进入页面时的圆形进度条
  bool firstGet = true;

  ScrollController scrollController = ScrollController();

  @override
  /*void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        print('滑动到了最底部${scrollController.position.pixels}');
        setState(() {
          showMore = true;
        });
        getMoreData();
      }
    });
    //getListData();
  }*/

  @override
  Widget build(BuildContext context) {
    if (firstGet) {
      firstGet = false;
      getListData();
    }

    return Stack(
      children: <Widget>[
        RefreshIndicator(
          child: ListView.builder(
            controller: scrollController,
            itemCount: list.length + 1, //列表长度+底部加载中提示
            itemBuilder: choiceItemWidget,
            physics: new AlwaysScrollableScrollPhysics(),
          ),
          onRefresh: _onRefresh,
        ),
        Offstage(
          offstage: offState,
          child: Center(
            child: CircularProgressIndicator(),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
    //手动停止滑动监听
    scrollController.dispose();
  }

  /**
   * 加载哪个子组件
   */
  Widget choiceItemWidget(BuildContext context, int position) {
    if (position < list.length) {
      return PhoneListItem(position, list[position], (position) {
        debugPrint("点击了第$position条");
      });
    } else if (showMore) {
      return showMoreLoadingWidget();
    } else {
      return null;
    }
  }

  /**
   * 加载更多提示组件
   */
  Widget showMoreLoadingWidget() {
    return Container(
      height: 50.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '加载中...',
            style: TextStyle(fontSize: 16.0),
          ),
        ],
      ),
    );
  }

  void GetPhoneList(ok(dynamic)) {
    AppInherited app = AppContainer.of(context).app;

    app.mWebSocket.AddHandle("phone", (jsonMap) {
      app.mWebSocket.RemoveHandle("phone");

      var tLterClientInfoList = [];

      if (jsonMap["data"] != null) {
        int jsonMapDataLen = jsonMap["data"].length;
        for (int i = 0; i < jsonMapDataLen; i++) {
          PhoneInfo tPhoneInfo = PhoneInfo();
          tPhoneInfo.TellNum = jsonMap["data"][i]["tell_num"];
          tPhoneInfo.Imsi = jsonMap["data"][i]["imsi"];
          tPhoneInfo.OnTime = jsonMap["data"][i]["on_time"];
          tPhoneInfo.PcapCount = jsonMap["data"][i]["pcap_count"];
          tPhoneInfo.LterAddr = jsonMap["data"][i]["lter_addr"];

          tLterClientInfoList.add(tPhoneInfo);
        }
      }

      if (tLterClientInfoList.isEmpty) {
        Toast.snack(context, 'No mobile phone number was found !');
      }

      ok(tLterClientInfoList);
    });

    app.mWebSocket.Send("phone", app.mUser, null);
  }

  /**
   * 模拟进入页面获取数据
   */
  void getListData() async {
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
    });

    GetPhoneList((tLterClientInfoList) {
      setState(() {
        isLoading = false;
        offState = true;
        list = tLterClientInfoList;
      });
    });
  }

  /**
   * 模拟到底部加载更多数据
   */
  void getMoreData() async {
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
      page++;
    });
    print('上拉刷新开始,page = $page');
    await Future.delayed(Duration(seconds: 1), () {
      setState(() {
        isLoading = false;
        showMore = false;
        list.addAll(List.generate(3, (i) {
          PhoneInfo phoneInfo = PhoneInfo();
          phoneInfo.TellNum = "1996201862$i";
          return phoneInfo;
        }));
        print('上拉刷新结束,page = $page');
      });
    });
  }

  /**
   * 模拟下拉刷新
   */
  Future<void> _onRefresh() async {
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
      page = 0;
    });

    print('下拉刷新开始,page = $page');

    GetPhoneList((tLterClientInfoList) {
      setState(() {
        isLoading = false;
        list = tLterClientInfoList;
      });
    });

    /*await Future.delayed(Duration(seconds: 1), () {
      setState(() {
        isLoading = false;

        List tempList = List.generate(3, (i) {
          PhoneInfo phoneInfo = PhoneInfo();
          phoneInfo.TellNum = "1899400015$i";
          return phoneInfo;
        });
        tempList.addAll(list);
        list = tempList;
        print('下拉刷新结束,page = $page');
      });
    });*/
  }
}

/**
 * 下拉刷新组件
 *const RefreshIndicator
    ({
    Key key,
    @required this.child,
    this.displacement: 40.0, //触发下拉刷新的距离
    @required this.onRefresh, //下拉回调方法,方法需要有async和await关键字，没有await，刷新图标立马消失，没有async，刷新图标不会消失
    this.color, //进度指示器前景色 默认为系统主题色
    this.backgroundColor, //背景色
    this.notificationPredicate: defaultScrollNotificationPredicate,
    })
 */
